package com.oneinlet.controller;

import com.oneinlet.YCStream;
import com.oneinlet.entity.User;
import com.oneinlet.service.RedisService;
import com.oneinlet.service.UserService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * Created by WangZiHe on 2017/11/5
 * QQ/WeChat:648830605
 * QQ-Group:368512253
 * Blog:www.520code.net
 * Github:https://github.com/yancheng199287
 */

@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisService redisService;

    @RequestMapping("/putValueToRedis/{name}")
    public Object getRedis(@PathVariable String name) {
        redisService.setKeyValue(name, "www.520code.net");
        return setOKResult();
    }

    @RequestMapping("/save")
    public Object save(User user) {
        user.setAge(25);
        System.out.println(ToStringBuilder.reflectionToString(user));
        return setOKResult(userService.save(user));
    }

    @GetMapping("/select")
    public Object select() {
        return setOKResult(userService.findAll());
    }


    @GetMapping("/update/{id}")
    public Object update(@PathVariable("id") Integer id) {
        User user = userService.getOne(id);
        user.setAddress("湖北武汉");
        return setOKResult(userService.save(user));
    }

    @GetMapping("/delete/{id}")
    public Object delete(@PathVariable("id") Integer id) {
        userService.deleteById(id);
        return setOKResult();
    }

    // 使用form-data形式支持多文件和多个键值对上传
    @RequestMapping(value = "/uploadFile", consumes = "multipart/form-data")
    public Object uploadFile(@RequestParam("username") String username, @RequestParam("imgFile") MultipartFile imgFile, @RequestParam("docFile") MultipartFile docFile) throws IOException {
        imgFile.transferTo(new File("save path"));
        docFile.transferTo(new File("save path"));
        return setOKResult();
    }

    // 下载文件，无法使用ajax下载文件，使用a标签跳转链接吧
    @RequestMapping(value = "/downloadFile")
    public Object uploadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String path = "C:\\Users\\MAC\\Desktop\\内网穿透更新说明.txt";
        //如果下载名是中文，则文件名需要经过url编码URLEncoder.encode(filename,"UTF-8")(平常直接+文件名即可)
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("内网穿透更新说明.txt", "UTF-8"));
        OutputStream out = response.getOutputStream();
        YCStream.INSTANCE.write(new FileInputStream(new File(path)), out);
        out.flush();
        return setOKResult();
    }


}
